package im.youni.horus.core.common;

import java.io.IOException;
import java.net.ServerSocket;

public class ServerPortUtils {

    /**
     * 获取可用端口
     * @return
     */
    static int max = 13000;
    static int min = 12000;

    public static int getAvailablePort() {
        int port = min;
        boolean using = ServerPortUtils.isLocalPortUsing(port);
        if (using) {
            if (min < max) {
                min = min + 1;
            } else {
                throw new RuntimeException("没有可用的端口");
            }
            return getAvailablePort();
        } else {
            return port;
        }
    }

    /**
     * 测试本机端口是否被使用
     * @param port
     * @return
     */
    public static boolean isLocalPortUsing(int port) {
        boolean flag = isPortUsing(port);
        return flag;
    }

    /***
     * 测试主机Host的port端口是否被使用
     *
     * @param port
     * @throws
     */
    public static boolean isPortUsing(int port) {
        ServerSocket s = null;
        try {
            s = new ServerSocket(port);
        } catch (IOException e) {
            if (e instanceof java.net.BindException) {
                System.err.println("autoserverport检测到 端口正在使用,port=" + port);
                return true;
            }
        } finally {
            try {
                if (s != null) {
                    s.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;

    }
}
